<?php

/**
 * 
 * @version $Id: Login.php 2 2012-05-26 02:24:18Z joaopaulopvillela@gmail.com $
 */
class Model_Mapper_Login extends App_Model_Mapper_Abstract 
{
	/**
	 * 
	 * @access 	public
	 * @param 	int $limit
	 * @return 	Zend_Db_Table_Rowset
	 */
	public function fetchInactiveUsers ( $limit = 5 )
	{
		$dbUsuario = App_Model_DbTable_Factory::get('Usuario');
		$dbLogin = App_Model_DbTable_Factory::get('Login');
		
		$select = $dbLogin->select()
			->setIntegrityCheck(false)
			->from(
				array('l' => $dbLogin),
				array('nome')
			)
			->join(
				array('u' => $dbUsuario),
				'u.login_id = l.id',
				array('serial')
			)
			->where('liberado = :liberado')
			->where('nivel = :nivel')
			->where('hash IS NULL')
			->order('dt_cadastro')
			->limit( $limit )
			->bind(
				array(
					':liberado' => 0,
					':nivel' 	=> 'U',
				)
			);
			
		$rows = $dbLogin->fetchAll( $select );
		
		return $rows;
	}
	
	/**
	 * 
	 * @access public
	 * @return void
	 */
	public function save ()
	{
		try {

			$dbLogin = App_Model_DbTable_Factory::get('Login');
			
			$where = array('email = ?' => $this->_data['email']);
			
			if ( !$dbLogin->isUnique($where, $this->_data['id']) ) {
				$this->_message->addMessage('Este e-mail esta sendo utilizado, escolha outro.', App_Message::WARNING);
				return false;
			}
			
			//Remove o indice nivel, pois ao realizar update o mesmo nao pode ser alterado
			if ( !empty($this->_data['id']) )
				unset($this->_data['nivel']);
				
			//Verifica senha
			if ( empty($this->_data['senha']) )
				unset($this->_data['senha']);
			else
				$this->_data['senha'] = sha1($this->_data['senha']);
			
			return parent::_simpleSave( $dbLogin );
			
		} catch ( Exception $e ) {

			$this->_message->addMessage( $this->_config->message->error, App_Message::ERROR );
			
			return false;
			
		}
	}
	
	/**
	 * (non-PHPdoc)
	 * @see App_Model_Mapper_Abstract::fetchAll()
	 */
	public function fetchAll ()
	{
		$dbLogin 	= App_Model_DbTable_Factory::get('Login'); 
		$dbUsuario 	= App_Model_DbTable_Factory::get('Usuario');
		
		$select = $dbLogin->select()
			->setIntegrityCheck(false)
			->from(
				array('l' => $dbLogin),
				array('id', 'nome', 'email', 'nivel', 'liberado', 'dt_cadastro')
			)
			->joinLeft(
				array('u' => $dbUsuario),
				'u.login_id = l.id',
				array('serial')
			);
			
		$rows = $dbLogin->fetchAll( $select );
		
		return $rows;
	}
	
	/**
	 * 
	 * @access public
	 * @return Zend_Db_Table_Row
	 */
	public function fetchRow ()
	{
		$dbLogin = App_Model_DbTable_Factory::get('Login');
		
		return parent::_simpleFetchRow($dbLogin);
	}
	
	/**
	 * 
	 * @access 	public
	 * @param 	array $param
	 * @return 	boolean
	 */
	public function updateStatus ( array $param )
	{
		$dbLogin = App_Model_DbTable_Factory::get('Login');
		
		if ( !empty($param['action']) ) {
		
			$select = $dbLogin->select()
				->from(
					array('l' => $dbLogin),
					array('id', 'nome', 'email')
				)
				->where('id IN(?)', $param)
				->where('hash IS NULL');
				
			$rows = $dbLogin->fetchAll( $select );
		
			if ( $rows->count() ) {
				
				foreach ( $rows as $row ) {
					
					//Grava senha
					$senha = App_General_Password::getRand();
					
					$data = array( 
						'senha' => sha1($senha),
						'hash' => md5(uniqid(time())) 
					);
					
					$where = $dbLogin->getAdapter()->quoteInto('id = ?', $row->id);
					
					$dbLogin->update($data, $where);
									
					//Manda e-mail
					$path = APPLICATION_PATH . '/modules/admin/views/scripts/login/';
					
					$result = array(
						'nome' 	=> $row->nome,
						'email' => $row->email,
						'senha' => $senha
					);
					
					$view = new Zend_View();
					$view->setScriptPath( $path );
					$view->assign( 'result', $result );
					
					$mail = new Zend_Mail( 'utf-8' );
					
					$mail->addTo( $row->email, $row->nome );
					$mail->setSubject( 'Senha - ' . $this->_config->geral->title );
					$mail->setBodyHtml( $view->render( 'mail-confirm.phtml' ) );
					$mail->setFrom( $this->_config->email->address, $this->_config->email->name );
					
					$mail->send();
					
				}
				
			}
			
		}
		
		return parent::_updateStatus($dbLogin, $param);
	}
	
	/**
	 * 
	 * @access public
	 * @return boolean
	 */
	public function delete ()
	{
		try {
			
			$rowCount = 0;
			
			$adapter = Zend_Db_Table::getDefaultAdapter();
			
			$adapter->beginTransaction();
			
			$dbUsuairo = App_Model_DbTable_Factory::get('Usuario');
			$rowCount += $dbUsuairo->delete( array('login_id = ?' => $this->_data['id']) ); 
			
			$dbLogin = App_Model_DbTable_Factory::get('Login');
			$rowCount += $dbLogin->delete( array('id = ?' => $this->_data['id']) ); 
			
			$adapter->commit();
			
			return !empty($rowCount);
			
		} catch ( Exception $e ) {
			
			$adapter->rollBack();
			
			return false;
			
		}
	}
}